#!/bin/bash

PRE_CMD='redis-cli --no-auth-warning -a {{ redis_auth_pass }} -h {{ global_bond_ip }} -p {{ redis_port }}'

# Check if a master is failed
FAILED_MASTER=$(${PRE_CMD} CLUSTER NODES | grep -v grep | grep master | grep fail | tail -n1 | awk '{print $1}')

if [[ ! -z ${FAILED_MASTER} ]]; then
  REPLICA_NODE=$(${PRE_CMD} CLUSTER NODES | grep -v grep | grep slave | grep ${FAILED_MASTER} | tail -n1 | awk '{print $2}')

  if [[ ! -z ${REPLICA_NODE} ]]; then

    IFS=':'

    read -ra HOST <<< ${REPLICA_NODE}

    IFS='@'

    read -ra PORTS <<< ${HOST[1]}

    redis-cli --no-auth-warning -a {{ redis_auth_pass }} -h ${HOST[0]} -p ${PORTS[0]} CLUSTER FAILOVER TAKEOVER
  
  else
  
    echo "Something is wrong! no replica for master ${FAILED_MASTER}"

    exit 1
  
  fi

else

  echo 'Great! Nothing is wrong!'

fi

